package ce51.dunghn.displaytest;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class DisplayAdapter extends ArrayAdapter<String> {
	static ArrayList<String> array;
	int resource;
	Context context;

	public DisplayAdapter(Context context, int textViewResourceId,
			ArrayList<String> objects) {
		super(context, textViewResourceId, objects);
		this.context = context;
		resource = textViewResourceId;
		array = objects;
	}

	@Override
	public int getCount() {
		return array.size();
	}

	@Override
	public String getItem(int position) {
		return array.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View v = convertView;
		if (v == null) {
			v = new DisplayViewCustom(getContext());
		}
		final String mString = array.get(position);
		if (mString != null) {
			ImageView img = ((DisplayViewCustom) v).img;
			TextView txt = ((DisplayViewCustom) v).txt;
			if (mString.startsWith("http://") && mString.endsWith(".jpg")) {
				try {
					img.setVisibility(View.VISIBLE);
					img.setImageDrawable(grabImageFromUrl(mString));
				} catch (Exception e) {
				}
				txt.setVisibility(View.GONE);
			} else {
				img.setVisibility(View.GONE);
				txt.setVisibility(View.VISIBLE);
				txt.setText(mString);
			}
		}
		return v;
	}

	private Drawable grabImageFromUrl(String url) throws Exception {
		return Drawable.createFromStream(
				(InputStream) new URL(url).getContent(), "src");
	}
}
